<?php

namespace app\admin\controller;

use think\Db;
use think\Controller;

class Bus extends Controller
{
    public function e1()
    {
        return view();
    }

    public function e2()
    {
        return view();
    }


    public function e3()
    {

        sleep(4);

        return view();
    }

    public function e()
    {
        return view();
    }

    public function login()
    {
        //访问页面
        if ($this->request->isGet()) {
            return view();
        }

        //获取请求参数
        $username = input('username');
        $password = input('password');

        //验证
        strlen($username) < 4 && $this->error('登录账号长度不能少于4位有效字符!');
        strlen($password) < 4 && $this->error('登录密码长度不能少于4位有效字符!');
        // 用户信息验证
        $user = Db::table("s_user")->where(array("account" => $username, "password" => $password, "status" => "正常"))->find();
        if (empty($user)) {
            wlog("用户登陆", "登录失败，用户名:" . $username);
            $this->error('账号或密码或用户状态不正确，请重新输入!');
        }

        //更新最后登陆时间
//        Db::table("s_user")->where(["id"=>$user["id"]])->update(["last_login_time"=>time(),"last_login_ip"=>getClientIP()]);

        session('MAP_USER', $user["id"]);

        wlog("用户登陆", "登录成功，用户名:" . $username);

        $url = input("url");
        if (empty($url)) {
            $this->success('登录成功，正在进入系统...', "/");
        } else {
            $this->success('登录成功，正在进入系统...', $url);
        }

    }


    public function logout()
    {
        $user = get_user();
        session('MAP_USER', null);
        session_destroy();
        wlog("用户退出", "退出成功，用户名:" . $user["account"]);
        $this->success('退出登录成功！', '/admin/bus/login');
    }

    /**
     * 返回所有用户信息
     * by xj 2018/7/25
     */
    public function user_lst()
    {
        $key = input('param.key');
        $shift = input('shift');
        $map = [];
        if (!empty($shift)) {
            $map['shift'] = $shift;
        }
        // 新增部门id,查询检验员 (注: 用时注意!!!)
        //$map['position_id'] = 66;

        $map['name|account'] = ['like', '%' . urldecode($key) . '%'];
        $arr = db("s_user")->where($map)->limit(0, 999999)->field('id,name,\'0\' as degree')->select();
        return json($arr);
    }

    //获取页面按钮
    public function get_button()
    {

        $user = get_user();
        $user_id = $user['id'];
        $role_id = $user['role_id'];
        $menu_id = input("menu_id/d", 0);

        $sql = "select * from mh_s_button where status = '正常' and id in (select button_id from mh_s_menu_button where menu_id = $menu_id) and id in ( select button_id from mh_s_role_menu_button WHERE role_id = $role_id and menu_id = $menu_id union all select button_id from mh_s_user_menu_button WHERE user_id = $user_id and menu_id = $menu_id ) order by sort asc,category asc";
        $data = Db::query($sql);

        return json($data);
    }

    /**
     * 导出公共方法
     * User: ErXiao Date: 2019/6/7 20:00
     */
    public function export_data()
    {

        //获取模块控制器方法
        $m = input("param.eee_m");//获取数据的模块
        $c = input("param.eee_c");//获取数据的控制器
        $f = input("param.eee_f");//获取数据的方法
        $c = ucfirst($c);//大写控制器第一个字母
        $title = input("param.eee_t");//获取页面标题
        $colstr = input("param.eee_l");
        $col = json_decode($colstr);//获取表格列

        //表格头行数
        $header_rows = count($col);

        //表格列数
        $header_cols = 0;
        for ($i = 0; $i < count($col[0]); $i++) {
            if (isset($col[0][$i]->colspan)) {
                $header_cols += $col[0][$i]->colspan;
            } else {
                $header_cols += 1;
            }
        }

        //excel列名称
        $columnName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        //反射获取数据
        $class = "app\\" . $m . "\\controller\\" . $c;
        $class = new ReflectionClass($class);
        $instance = $class->newInstanceArgs();
        $method = $class->getmethod($f);
        $obj = $method->invoke($instance);
        $data = $obj->getData();

        if (array_key_exists("rows", $data)) {
            $data = $data["rows"];
        }
        $rows = count($data);

        //创建excel对象
        $objPHPExcel = new \PHPExcel();

        //设置excel属性
        $Creator = iconv('utf-8', 'gb2312', "苏州普腾信息科技有限公司");
        $LastModifiedBy = iconv('utf-8', 'gb2312', "普腾软件");
        $Title = iconv('utf-8', 'gb2312', "Office 2007 XLSX Export Document");
        $Subject = iconv('utf-8', 'gb2312', "Office 2007 XLSX Export Document");
        $Description = iconv('utf-8', 'gb2312', "the document export from " . config("system_name"));

        $objPHPExcel->getProperties()->setCreator($Creator);
        $objPHPExcel->getProperties()->setLastModifiedBy($LastModifiedBy);
        $objPHPExcel->getProperties()->setTitle($Title);
        $objPHPExcel->getProperties()->setSubject($Subject);
        $objPHPExcel->getProperties()->setDescription($Description);

        //设置活动sheet
        $objPHPExcel->setActiveSheetIndex(0);

        //获取活动sheet
        $sheet = $objPHPExcel->getActiveSheet();

        //设置sheet标题
        $sheet->setTitle($title);

        //设置列宽
        for ($i = 0; $i < $header_cols; $i++) {
            $sheet->getColumnDimension($columnName[$i])->setWidth(15);
        }

        //设置边框颜色
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . "" . ($rows + $header_rows))->getBorders()->getAllBorders()->getColor()->setRGB('666666');
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . "" . ($rows + $header_rows))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

        //设置表头行高
        for ($i = 0; $i < $header_rows; $i++) {
            $sheet->getRowDimension($i + 1)->setRowHeight(25);
        }

        //设置表头加粗居中背景色
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . $header_rows)->getFont()->setBold(true);
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . $header_rows)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . $header_rows)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . $header_rows)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . $header_rows)->getFill()->getStartColor()->setRGB('c5d9f1');

        //设置数据字体大小
        $sheet->getStyle("A" . ($header_rows + 1) . ":" . $columnName[$header_cols - 1] . "" . ($rows + $header_rows + 1))->getFont()->setSize(10);


        //设置数据行高
        for ($i = 0; $i < count($data); $i++) {
            $sheet->getRowDimension($i + $header_rows + 1)->setRowHeight(17);
        }

        //设置表头数据
        for ($i = 0; $i < count($col); $i++) {
            $col_index = 0;
            for ($j = 0; $j < count($col[$i]); $j++) {
                $cell = $columnName[$col_index];
                $cell = $cell . ($i + 1);
                $val = $col[$i][$j]->title;
                $sheet->SetCellValue($cell, $val);

                if (isset($col[$i][$j]->colspan)) {
                    $col_index += $col[$i][$j]->colspan;
                    $cell1 = $columnName[$col_index - 1];
                    $cell1 = $cell1 . ($i + 1);
                    $sheet->mergeCells($cell . ":" . $cell1);
                } else {
                    $col_index += 1;
                }
            }
        }

        //拼装数据
        for ($i = 0; $i < count($data); $i++) {
            for ($j = 0; $j < count($col[$header_rows - 1]); $j++) {
                $cell = $columnName[$j] . ($i + $header_rows + 1);
                $field = $col[$header_rows - 1][$j]->field;
                if (array_key_exists($field, $data[$i])) {
                    $type = $col[$header_rows - 1][$j]->type;
                    $val = $data[$i][$field];
                    if ($type == "Audit") {
                        switch ($val) {
                            case 0:
                                $val = '未审核';
                                break;
                            case 1:
                                $val = '审核已通过';
                                break;
                            case 2:
                                $val = '审核未通过';
                                break;
                            default:
                                $val = '未知';
                        }
                    } else if ($type == "Percent") {
                        if ($val == null || $val == 0) {
                            $val = "0.00%";
                        } else {

                            $val = sprintf("%.2f", bcmul(bcdiv($data[$i]["complate_qty"], $data[$i]["require_qty"], 5), 100, 3)) . '%';
                        }
                    }

                } else {
                    $val = "";
                }

                $sheet->SetCellValue($cell, $val);
            }
        }

        //设置边框颜色 放到最后焦点可以在右下角
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . "" . ($rows + $header_rows))->getBorders()->getAllBorders()->getColor()->setRGB('666666');
        $sheet->getStyle("A1:" . $columnName[$header_cols - 1] . "" . ($rows + $header_rows))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

        //输入导出信息
        $sheet->SetCellValue("A" . ($rows + $header_rows + 2), "Export");
        $sheet->SetCellValue("B" . ($rows + $header_rows + 2), ptdate());

        $sheet->SetCellValue("D" . ($rows + $header_rows + 2), "By");
        $sheet->SetCellValue("E" . ($rows + $header_rows + 2), get_user()['name']);

        //输出excel文件
        ob_end_clean();
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $title . '.xls"');
        header("Content-Disposition:attachment;filename=" . $title . ".xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    /**
     * 获取角色数据
     * User: ErXiao Date: 2019/8/15 13:57
     */
    public function get_role_data()
    {
        $data = Db::name('s_role')
            ->where(['is_delete' => 0])
            ->where("status = '正常' or status = 0")
            ->field('id,name')
            ->select();
        return info_msg($data);
    }

    /**
     * 获取职位数据
     * User: ErXiao Date: 2019/8/15 13:57
     */
    public function get_position_data()
    {
        $data = Db::name('s_position')
            ->where(['is_delete' => 0])
            ->where("status = '正常' or status = 0")
            ->field('id,name')
            ->select();
        return info_msg($data);
    }

    /**
     * 获取部门数据
     * User: ErXiao Date: 2019/8/15 13:57
     */
    public function get_department_data()
    {
        $data = Db::name('s_department')
            ->where(['is_delete' => 0])
            ->where("status = '正常' or status = 0")
            ->field('id,pid,name')
            ->select();
        $data = get_tree_data($data, 'id', 'pid', 'name');
        return info_msg($data);
    }

    /**
     * 获取部门数据
     * User: ErXiao Date: 2019/8/15 13:57
     */
    public function get_intention_data()
    {
        $data = Db::name('y_intention')->where(['is_delete' => 0])->field('id,number as name')->select();
        return info_msg($data);
    }

    /**
     *  获取客户数据
     * @author [Funk] Date: 2020/12/21 17:27
     */
    public function customer_lst()
    {
        $key = input('param.key');
        $map = [];
        $map['name|contacts'] = ['like', '%' . urldecode($key) . '%'];
        $data = Db::name('d_customer')->where(['is_delete' => 0])->field('id,name,number,contacts,telephone')->select();
        return json($data);
    }

    /**
     * 获取经纪人数据
     * User：erxiao.jia Date: 2021/1/7 上午10:41
     */
    public function get_agent_list()
    {
        $key = input('param.key');
        $map = [];
        $map['account|name'] = ['like', '%' . urldecode($key) . '%'];
        $map['role_id'] = 49;//角色ID等于 49 的所有用户
        $map['is_delete'] = 0;
        $data = Db::table('s_user')->where($map)->field('id,name')->select();
        return json($data);
        get_date();
    }

    /**
     * Name:
     * Author:wucj
     * DateTime:2021/3/15 16:09
     */
    public function get_port_list()
    {
        $key = input('key');

        $map = array();
        if (!empty($key)) {
            $map['name'] = array('like', "%$key%");
        }
        $data = Db::table('b_port')->where($map)->where(['status' => 0, 'is_delete' => 0])->field('id,name')->select();
        return json($data);
    }

    /**
     * Name:
     * Author:wucj
     * DateTime:2021/3/15 16:09
     */
    public function get_producer_list()
    {
        $key = input('key');

        $map = array();
        if (!empty($key)) {
            $map['name'] = array('like', "%$key%");
        }
        $data = Db::table('b_producers')->where($map)->where(['status' => 0, 'is_delete' => 0])->field('id,name')->select();
        return json($data);
    }

    /**
     * Name:
     * Author:wucj
     * DateTime:2021/3/15 16:09
     */
    public function get_supplier_list()
    {
        $key = input('key');

        $map = array();
        if (!empty($key)) {
            $map['name'] = array('like', "%$key%");
        }
        $data = Db::table('b_supplier')->where($map)->where(['status' => 0, 'is_delete' => 0])->field('id,name')->select();
        return json($data);
    }

    /**
     * Name:
     * Author:wucj
     * DateTime:2021/3/15 16:09
     */
    public function get_warehouse_list()
    {
        $key = input('key');

        $map = array();
        if (!empty($key)) {
            $map['name'] = array('like', "%$key%");
        }
        $data = Db::table('b_warehouse')->where($map)->where(['status' => 0, 'is_delete' => 0])->field('id,name')->select();
        return json($data);
    }

    /**
     * Name:
     * Author:wucj
     * DateTime:2021/3/15 16:09
     */
    public function get_purchaseorder_list()
    {
        $number = input('number');
        $container_number = input('container_number');

        $map = array();
        if (!empty($number)) {
            $map['number'] = array('like', "%$number%");
        }
        if (!empty($container_number)) {
            $map['container_number'] = array('like', "%$container_number%");
        }
        $data = Db::table('t_purchase_order')->where($map)->where(['status' => 0, 'is_delete' => 0])->field('id,number,container_number')->select();
        return json($data);
    }

    /**
     * use   获取歌手
     * user  Hugh
     * date  2021/5/19 18:39
     */
    public function singer()
    {
        $data = DB::name('b_singers')
              ->where(['is_delete'=>0])
              ->field('id,singer')
              ->select();
        return json($data);
    }
}
